<template>
  <div>
    <el-form :model="settingForm" label-width="80px" style="max-width: 500px">
      <el-form-item label="默认方案" :style="labelWidth">
        <el-row :gutter="20">
          <el-col :span="18">
            <el-select v-model="settingForm.defaultScheme" style="width: 250px">
              <el-option
                v-for="item in settingList"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-button type="primary" @click="onSetting">
              <el-icon><Setting /></el-icon>
              设 置
            </el-button>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item
        label="导出"
        :style="labelWidth"
        style="margin: 30px 0 30px 0"
      >
        <el-row :gutter="20">
          <el-col :span="18">
            <el-select v-model="settingForm.exportFile" style="width: 250px">
              <el-option
                v-for="item in settingList"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-button type="primary" @click="onExport">
              <el-icon><DocumentChecked /></el-icon>
              导 出
            </el-button>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="导入" :style="labelWidth">
        <el-upload
          v-model:file-list="settingForm.fileList"
          class="upload-demo"
          action="#"
          :accept="accept"
          :auto-upload="false"
          :limit="1"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :on-change="beforeUpload"
          :on-exceed="handleExceed"
        >
          <template #trigger>
            <el-button type="primary">选择文件</el-button>
          </template>
          <el-button
            style="margin-left: 10px"
            type="success"
            @click="submitUpload"
          >
            导入文件
          </el-button>
        </el-upload>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'

import {
  getSettingList,
  settingModel,
  importModel,
  exportModel
} from '@/api/template/modelSetting.js'
const labelWidth = ref('120px')
const accept = ref('.zip')
const settingForm = ref({
  defaultScheme: '',
  exportFile: '',
  fileList: []
})
const root = ref('/static_resource/model')
const settingList = ref([])
const resPath = ref('/static_resource/resource')
onMounted(() => {
  getList()
})

const getList = async () => {
  await getSettingList({ root: root.value })
    .then((res) => {
      settingList.value = res.data.list
      settingForm.value.defaultScheme = settingList.value[0]
      settingForm.value.exportFile = settingList.value[0]
    })
    .catch((err) => {
      console.log(err)
    })
}
// 设置
const onSetting = async () => {
  await settingModel({
    path: root.value,
    solution: settingForm.value.defaultScheme
  })
    .then((res) => {
      ElMessage({
        type: 'success',
        message: res.message
      })
    })
    .catch((err) => {
      console.log(err)
    })
}
// 导出文件
const onExport = async () => {
  try {
    const response = await exportModel({
      path: root.value,
      resPath: resPath.value,
      solution: settingForm.value.exportFile
    })
    // 确保 response 和 response.data 存在
    if (!response || !response.data) {
      throw new Error('No data received from server')
    }

    // 创建 Blob 对象
    const blob = new Blob([response.data], {
      type: response.headers['content-type'] || 'application/octet-stream'
    })
    const filename = `${settingForm.value.exportFile}.zip`
    // 创建一个临时的 <a> 元素用于下载
    const link = document.createElement('a')
    link.href = window.URL.createObjectURL(blob)
    link.download = filename

    // 将 <a> 元素添加到 DOM 中并触发点击事件
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    // 释放 Blob URL 资源
    window.URL.revokeObjectURL(link.href)
  } catch (error) {
    // console.error('Download failed:', error.message || error)
  }
}
// 文件预览
const handlePreview = (uploadFile) => {
  console.log('uploadFile', uploadFile)
}
// 文件删除
const handleRemove = (file, uploadFiles) => {
  console.log(file, uploadFiles)
}

const beforeUpload = (file) => {
  const typeArray = accept.value.split(',') || []
  const type = file.name.substring(file.name.lastIndexOf('.'))
  settingForm.value.fileList.push(file)
  if (!typeArray.includes(type)) {
    ElMessage.error(`只能上传${accept.value}格式的文件`)
    settingForm.value.fileList = []
    return false
  }
}

// 文件超出限制时触发
const handleExceed = (files, fileList) => {
  settingForm.value.fileList = [files[0]]
}

// 文件上传
const submitUpload = async () => {
  const formData = new FormData()
  settingForm.value.fileList.forEach((file) => {
    if (file.raw) {
      formData.append('tplZip', file.raw)
    }
  })

  for (const pair of formData.entries()) {
    console.log(pair[0] + ': ' + pair[1])
  }
  const source = settingForm.value.fileList[0].name.split('.')[0]
  await importModel(
    {
      path: '/static_resource/model',
      source: source,
      resPath: '/static_resource/resource'
    },
    formData
  ).then((res) => {
    if (res.success) {
      ElMessage.success('文件导入成功')
      settingForm.value.fileList = []
    } else {
      ElMessage.error('文件导入失败')
    }
  })
}
</script>

<style lang="scss" scoped>
:deep(.el-form-item__label) {
  font-weight: bold !important;
}
</style>
